import 'package:flutter/material.dart';
import '../model/ex_stream.dart';
import '../utils.dart';
import '../static_var.dart';
import '../widget/loading_widget.dart';
import '../widget/gradient_btn.dart';
import '../user_proof.dart';
import '../model/cus_dialog.dart';
import '../widget/red_point.dart';

class MsgDialog extends StatelessWidget {
  final ExStream<Map> msgStream;

  TextStyle dialogTextStyle = TextStyle(color: Colors.white, fontSize: 20);
  List<Map<String, String>> leftNavTitles = [{'k': '1', 't':'未读'}, {'k': '2', 't':'已读'}];
  List<Map<String, String>> topNavTitles = [{'k': '1', 't':'好友申请'}, {'k': '2', 't':'系统消息'}];

  ExStream<String> dialogTopSelectedStream;
  ExStream<String> dialogLeftSelectedStream;
  ExStream<List<Map>> dialogInfoStream = ExStream<List<Map>>(null);
  BuildContext widgetContext;

  Map msgDataCache;

  MsgDialog({@required this.msgStream}) {
    dialogTopSelectedStream = ExStream<String>(topNavTitles[0]['k']);
    dialogLeftSelectedStream = ExStream<String>(leftNavTitles[0]['k']);
  }
  void initLeftSelected() {
    dialogLeftSelectedStream.setData(leftNavTitles[0]['k']);
  }

  void getMessage() async {
    dialogInfoStream.setData(null);
    Utils.get(context: this.widgetContext, url: StaticVar.remoteUrl + '/getMessage', data: {'user_id':UserProof.userId, 'msg_type':dialogTopSelectedStream.data, 'msg_status':dialogLeftSelectedStream.data}, success: (res){
      dialogInfoStream.setData(List.from(res['data']));
    });
  }
  void scanMessage({String msgId = ''}) async {
    dialogInfoStream.setData(null);
    Utils.get(context: this.widgetContext, url: StaticVar.remoteUrl + '/scanMessage', data: {'user_id':UserProof.userId, 'msg_type':dialogTopSelectedStream.data, 'msg_id':msgId}, success: (res){
      CusDialog.showSuc(widgetContext, '处理成功');
    });
  }
  void clearScanedMsg() async {
    dialogInfoStream.setData(null);
    Utils.get(context: this.widgetContext, url: StaticVar.remoteUrl + '/clearScanedMsg', data: {'user_id':UserProof.userId, 'msg_type':dialogTopSelectedStream.data}, success: (res){
      CusDialog.showSuc(widgetContext, '处理成功');
      this.getMessage();
    });
  }

  Widget getMessageDialogTitle(String title, {@required VoidCallback callback, bool isSelected=false, bool isBoldFont = false}) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      child: Container(
        alignment: Alignment.center,
        padding: EdgeInsets.symmetric(vertical: 8, horizontal: 0),
        child: Text(title, style: TextStyle(color: isSelected?Colors.white:Colors.grey, fontSize: 20, fontWeight: isBoldFont ? FontWeight.bold:FontWeight.normal),),
      ),
      onTap: callback,
    );
  }
  Widget getMessageWidgetContainer({Widget child}) {
    return Card(
      color: Color.fromARGB(125, 27,74,161),
      child: Container(
        padding: EdgeInsets.only(top: 5, bottom: 10,left: 15, right: 15),
        child: child
      )
    );
  }
  Widget getTimeWidget(String timeStr) {
    return Text(Utils.formatDatetime(DateTime.fromMillisecondsSinceEpoch(int.parse(timeStr))), style: TextStyle(color: StaticVar.greyColor, fontSize: 12));
  }
  Widget getMessagesWidget(List<Map> msgs, bool hasScan) {
    if(null != msgs && msgs.length > 0) {
      List<Widget> msgWidgets = [];

      if((dialogTopSelectedStream.data == '2' && dialogLeftSelectedStream.data=='1')||dialogLeftSelectedStream.data=='2') {
        msgWidgets.add(
          Container(
            padding: EdgeInsets.only(right: 8, bottom: 8),
            alignment: Alignment.centerRight,
            child: dialogLeftSelectedStream.data=='2'?GradientBtn(child: Text('清空已读', style: TextStyle(fontSize: 15, color: Colors.white),), width: 75, height: 23, colorType: 2, pressed: (){
              clearScanedMsg();
            },) : GradientBtn(child: Text('全部已读', style: TextStyle(fontSize: 15, color: Colors.white),), width: 75, height: 23, pressed: (){
              scanMessage();
            },)
          )
        );
      }
      msgs.forEach((msg){
        if(msg['type'] == 1) {
          msgWidgets.add(
            getMessageWidgetContainer(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  RichText(
                    text: TextSpan(
                      children: [
                        TextSpan(text: msg['send_uname'].toString(), style: TextStyle(color: StaticVar.yellowColor)),
                        TextSpan(text: '  申请加您为好友')
                      ]
                    )
                  ),
                  hasScan ? Container(
                      margin: EdgeInsets.only(top: 3),
                      child: getTimeWidget(msg['time']),
                    ) : Column(
                    children: <Widget>[
                      Container(height: 3,),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        crossAxisAlignment: CrossAxisAlignment.end,
                        children: <Widget>[
                          getTimeWidget(msg['time']),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.end,
                            children: <Widget>[
                              GradientBtn(child: Text('拒绝', style: TextStyle(fontSize: 15, color: Colors.white),), width: 55, height: 20, pressed: (){
                                solveFriendApply(msg['id'], false);
                              },),
                              Container(width: 15,),
                              GradientBtn(child: Text('同意', style: TextStyle(fontSize: 15, color: Colors.white),), width: 55, height: 20, colorType: 2, pressed: (){
                                solveFriendApply(msg['id'], true);
                              },),
                            ],
                          )
                        ],
                      )
                    ],
                  )
                ],
              ),
            ),
          );
        }else {
          if(msg['type'] == 2) {
            msgWidgets.add(
              getMessageWidgetContainer(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(msg['content'].toString(), style: TextStyle(color: Colors.white)),
                    hasScan ? Container(
                      margin: EdgeInsets.only(top: 3),
                      child: getTimeWidget(msg['time']),
                    ) : Column(
                    children: <Widget>[
                      Container(height: 5,),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: <Widget>[
                          getTimeWidget(msg['time']),
                          GradientBtn(child: Text('已读', style: TextStyle(fontSize: 15, color: Colors.white),), width: 55, height: 20, colorType: 2, pressed: (){
                            scanMessage(msgId: msg['id'].toString());
                          },),
                        ],
                      )
                    ])
                  ],
                )
              )
            );
          }
        }
      });
      return ListView(
        padding: EdgeInsets.all(5),
        children: msgWidgets,
      );
    }else {
      return Container(
        alignment: Alignment.center,
        child: Text('暂无数据', style: TextStyle(color: StaticVar.greyColor)),
      );
    }
  }

  void solveFriendApply(int msgId, bool isAgree) async {
    Utils.get(context: this.widgetContext, url: StaticVar.remoteUrl + '/solveAddFriend', data: {'user_id':UserProof.userId, 'msg_id':msgId, 'is_agree': isAgree}, success: (res){
      CusDialog.showSuc(this.widgetContext, '处理成功');
    });
  }

  @override
  Widget build(BuildContext context) {
    this.widgetContext = context;

    Size screenSize = MediaQuery.of(context).size;
    double listViewWidth = screenSize.width / 2;
    double listViewHeight = screenSize.height / 2;
    
    return SimpleDialog(
      backgroundColor: Color.fromARGB(255, 2,29,55),
      titlePadding: EdgeInsets.symmetric(vertical: 2, horizontal: 5),
      title: StreamBuilder<Map>(
        stream: msgStream.stream,
        initialData: msgStream.data,
        builder: (BuildContext context, AsyncSnapshot<Map> msgData) {
          Map msgDetail = msgData.data['detail'];
          if(null == msgDataCache || (dialogLeftSelectedStream.data=='1' && msgDataCache[this.dialogTopSelectedStream.data] != msgDetail[this.dialogTopSelectedStream.data])) {
            getMessage();
          }
          msgDataCache = msgDetail;

          return StreamBuilder<String>(
            stream: dialogTopSelectedStream.stream,
            initialData: dialogTopSelectedStream.data,
            builder: (BuildContext context, AsyncSnapshot<String> data) {
              List<Widget> topNavWidgets = [];
              String selectKey = data.data;
              topNavTitles.forEach((Map<String, String> title){
                topNavWidgets.add(Container(
                  padding: EdgeInsets.symmetric(vertical: 2, horizontal: 10),
                  child: Stack(
                    overflow: Overflow.visible,
                    children: <Widget>[
                      getMessageDialogTitle(title['t'], isBoldFont: true, isSelected: title['k']==selectKey, callback: (){
                        dialogTopSelectedStream.setData(title['k']);
                        initLeftSelected();
                        this.getMessage();
                      }),
                      RedPoint(count: msgDetail[title['k']], offsetX: -1, offsetY: 5,)
                    ],
                  ),
                ));
              });
              return Container(
                decoration: BoxDecoration(
                  border: Border(bottom: BorderSide(color: Colors.white))
                ),
                child: Row(
                  children: topNavWidgets,
                ),
              );
            }
          );
        },
      ),
      children: <Widget>[
        Row(
          children: <Widget>[
            Container(
              width: 106,
              height: listViewHeight,
              decoration: BoxDecoration(
                border: Border(right: BorderSide(color: Colors.white, width: 1))
              ),
              
              child: StreamBuilder<String>(
                stream: dialogLeftSelectedStream.stream,
                initialData: dialogLeftSelectedStream.data,
                builder: (BuildContext context, AsyncSnapshot<String> data) {
                  List<Widget> titleWidgets = [];
                  String selectedTitle = data.data;

                  leftNavTitles.forEach((Map<String, String> title) {
                    titleWidgets.add(getMessageDialogTitle(title['t'], isSelected: title['k'] == selectedTitle, callback: (){
                      dialogLeftSelectedStream.setData(title['k']);
                      this.getMessage();
                    }));
                  });
                  
                  return ListView(
                    children: titleWidgets,
                  );
                },
              ),
            ),
            Expanded(
              child: Container(
                width: listViewWidth,
                height: listViewHeight,
                child: StreamBuilder<List<Map>>(
                  stream: dialogInfoStream.stream,
                  initialData: dialogInfoStream.data,
                  builder: (BuildContext context, AsyncSnapshot<List<Map>> data) {
                    List<Map> infoData = data.data;
                    return null == infoData?LoadingWidget(hasBk: false,) :  getMessagesWidget(infoData, dialogLeftSelectedStream.data=='2');
                  },
                )
              )
            )
            
          ],
        )
      ],
    );
  }
}